const { createClient } = require('redis');

class RedisClient {
    constructor() {
        if (RedisClient.instance) {
            return RedisClient.instance;
        }

        this.client = null;
        this.isConnected = false;
        RedisClient.instance = this;
    }

    /**
     * 初始化Redis连接（Express启动时调用一次）
     */
    async init() {
        if (this.isConnected) {
            console.log('Redis already connected');
            return this.client;
        }

        try {
            this.client = createClient({
                socket: {
                    host: process.env.REDIS_HOST || 'localhost',
                    port: process.env.REDIS_PORT || 6379,
                    reconnectStrategy: (retries) => {
                        if (retries > 10) {
                            console.log('Too many Redis connection retries');
                            return new Error('Too many retries');
                        }
                        return Math.min(retries * 100, 3000);
                    }
                },
                password: process.env.REDIS_PASSWORD || undefined,
                database: process.env.REDIS_DB || 0
            });

            // 绑定事件处理器
            this.client.on('connect', () => {
                console.log('Redis client connecting...');
            });

            this.client.on('ready', () => {
                console.log('✅ Redis client ready');
                this.isConnected = true;
            });

            this.client.on('error', (err) => {
                console.error('❌ Redis client error:', err);
                this.isConnected = false;
            });

            this.client.on('end', () => {
                console.log('Redis connection closed');
                this.isConnected = false;
            });

            this.client.on('reconnecting', () => {
                console.log('Redis client reconnecting...');
            });

            // 连接Redis
            await this.client.connect();
            console.log('✅ Redis connection established successfully');

            return this.client;

        } catch (error) {
            console.error('❌ Failed to initialize Redis:', error);
            throw error;
        }
    }

    /**
     * 获取Redis客户端实例（在其他地方直接调用）
     */
    getClient() {
        if (!this.client || !this.isConnected) {
            throw new Error('Redis client not initialized. Call init() first.');
        }
        return this.client;
    }

    /**
     * 检查连接状态
     */
    isReady() {
        return this.isConnected && this.client && this.client.isReady;
    }

    /**
     * 关闭Redis连接
     */
    async disconnect() {
        if (this.client) {
            await this.client.quit();
            this.isConnected = false;
            this.client = null;
            console.log('Redis connection closed gracefully');
        }
    }

    /**
     * Ping Redis服务器
     */
    async ping() {
        try {
            const client = this.getClient();
            return await client.ping();
        } catch (error) {
            console.error('Redis ping failed:', error);
            return false;
        }
    }
}

// 创建并导出单例实例
const redisClient = new RedisClient();
module.exports = redisClient;